package de.unikoblenz.west.csxpoi;

import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.TimeZone;

import de.unikoblenz.west.csxpoi.R;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;

/**
 * DatePickerActivity shows a separate window, where the user can set a date and
 * send it back to the csxPOI activity.
 * 
 * @author Daniel Schmeiss
 * 
 */
public class DatePickerActivity extends Activity {

	/**
	 * the {@link DatePicker}
	 */
	private DatePicker mDate;

	/**
	 * control buttons at the bottom of this activity
	 */
	private Button mCancelButton, mSaveButton, mTodayButton;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.date_picker_activity);

		mDate = (DatePicker) findViewById(R.id.date_picker_picker);
		mCancelButton = (Button) findViewById(R.id.date_picker_cancel_button);
		mSaveButton = (Button) findViewById(R.id.date_picker_save_button);
		mTodayButton = (Button) findViewById(R.id.date_picker_today_button);

		mDate.setVisibility(View.VISIBLE);

		Bundle extras = getIntent().getExtras();

		// update the date, if no date is given, finish
		if (extras != null) {
			mDate.updateDate(extras.getInt("year"), extras.getInt("month"),
					extras.getInt("day"));
		} else {
			finish();
		}

		mCancelButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});

		mSaveButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				returnResult();
			}
		});

		mTodayButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Calendar cal = new GregorianCalendar(TimeZone.getDefault());
				mDate.updateDate(cal.get(Calendar.YEAR), cal
						.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH));
			}
		});

	}

	/**
	 * returnResult creates and sends an intent to the {@link CsxPoiActivity},
	 * that contains the chosen date.
	 */
	private void returnResult() {
		Intent resultIntent = new Intent(DatePickerActivity.this,
				CsxPoiActivity.class);
		resultIntent.putExtra("year", mDate.getYear());
		resultIntent.putExtra("month", mDate.getMonth());
		resultIntent.putExtra("day", mDate.getDayOfMonth());
		setResult(RESULT_OK, resultIntent);
		finish();
	}
}
